package com.wcong.controller;

import com.wcong.pojo.Book;
import com.wcong.service.impl.BookServiceImpl;
import com.wcong.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author wcong
 * @version 1.0
 * @date 2020-09-23 23:39
 */
@Controller
@RequestMapping("/book")
public class BooksController {

    @Autowired
    private BookServiceImpl bookService;

    @GetMapping("/books")
    public String bookList(Model model){
        List<Book> bookList = bookService.getByList();
        model.addAttribute("books",bookList);
        return "allBooks";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addPaper(Book book) {
        book.setBookID((int) new IdWorker().nextId());
        System.out.println(book);
        bookService.insertBook(book);
        return "redirect:/book/books";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
        Book books = bookService.getById(id);
        System.out.println(books);
        model.addAttribute("book",books);
        return "updateBook";
    }

    /**
     * 更新
     * @param book
     * @return
     */
    @RequestMapping("/updateBook")
    public String updateBook(Book book) {
        System.out.println("update --> " + book.toString());
        bookService.updateBook(book);
        /*Book books = bookService.getById(book.getBookID());
        model.addAttribute("books", books);*/
        return "redirect:/book/books";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/books";
    }

}
